<script>
export default {
  name:"staffManage",
  data() {
    let checkStaffName =(rule,value,callback)=>{
      if(this.form.id){
        return callback();
      }
      this.$axios.post("/zzh-staff/findeByLoginName?loginName="+this.form.loginName).then(res=>res.data).then(res=>{
        console.log(res.data)
        if(res.resultCode!=200){
          callback()
        }else{
          callback(new Error('登录账号已经存在'));
        }
      })
    };
    return {
      tableData: [],
      hashMapRoles:{},
      hashMapOrganizations:{},
      pageNum:1,
      pageSize:5,
      total:5,
      username:'',
      department:'',
      TreeData:[],
      selectedNode:[],
      selectedValue: null,
      selectedNodeDialog:[],
      selectedValueDialog: null,
      defaultProps: {
        valueL:'id',
        children: 'children',
        label: 'label'
      },
      dialogVisible:false,
      loading: true,
      form:{
        username:'',
        loginName:'',
        position:'',
        department:'',
        email:'',
        phonenum:'',
        description:'',
        remark:''
      },
      rules: {
        loginName: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { min: 4, max: 18, message: '长度在 4 到 18 个字符', trigger: 'blur' },
          {validator:checkStaffName,trigger: 'blur'}
        ],
        username: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        position: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        department: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        phonenum: [
          {required: true,message: "⼿机号不能为空",trigger: "blur"},
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输⼊正确的⼿机号码", trigger: "blur"}
        ],
      }
    };
  },
  methods:{
    //查询下拉角色和部门列表
    loadOption(){
      this.$axios.get('/zzh-staff/option').then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.hashMapRoles = res.data.hashMapRoles;
          this.hashMapOrganizations = res.data.hashMapOrganizations;
        }else {
          alert('获取数据失败')
        }
      })
      this.$axios.get('/zzh-organization/list').then(res=>res.data).then(res=>{
        this.loading = false;
        if(res.resultCode==200){
          this.TreeData=res.data
        }else {
          alert('获取数据失败')
        }
      })
    },
    //查询所有员工信息
    loadPost(){
      this.loading = true;
      this.$axios.post('/zzh-staff/list',{
        page:this.pageNum,
        limit:this.pageSize,
        username:this.username,
        department:this.department
      }).then(res=>res.data).then(res=>{
        this.loading = false;
        if(res.resultCode==200){
          this.tableData=res.data
          this.total=res.total
        }else {
          alert('获取数据失败')
        }
      })
    },
    //导出数据
    exportExcel() {
      //将响应数据类型设置为 Blob 对象   原因: 确保文件等二进制数据在传输过程中不会被转换或解析,对于文件下载非常有用，因为你可以直接将返回的二进制数据用于创建可下载的文件
      this.$axios.post('/zzh-excel/staffExcel',this.tableData, { responseType: 'blob' })
          .then(response => {
            // 将获取到的Excel数据转换为文件
            //Blob是二进制的容器，可以存放任意类型的二进制文件：图片/音频/文件
            //type : 类型设为Excel文件（.xlsx）的MIME类型，告诉浏览器创建的是一个Excel文件，默认使用excel打开
            const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

            // 创建隐藏的下载链接并模拟点击下载
            const link = document.createElement('a');
            //创建一个可供用户下载的链接
            link.href = URL.createObjectURL(blob);
            link.download = '员工信息表格.xlsx';
            //设置链接的打开方式为新标签页（_blank），这样用户点击链接后会在新标签页中下载文件
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          })
          .catch(error => {
            console.error(error);
          });
    },
    //点击添加按钮，弹出添加对话框
    add(){
      this.dialogVisible=true
      this.$nextTick(()=>{
        this.resetForm()
      })
    },
    //判断点击了修改按钮还是添加按钮
    loadAdd(){
      //表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          if(this.form.id){
            this.doUpdate();
            this.form.id=''
          }else {
            this.doAdd()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //进行添加操作
    doAdd(){
      this.$axios.post('/zzh-staff/add',this.form).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.dialogVisible=false;
          this.resetForm();
          this.$message({
            showClose: true,
            message: '新增数据成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '新增数据失败',
            type: 'error'
          });
        }
      })
    },
    //进行更新前赋值操作
    mod(row){
      this.dialogVisible=true
      this.$nextTick(()=>{
        this.form.id=row.id
        this.form.username=row.username
        this.form.loginName=row.loginName
        this.form.position=row.position
        this.form.department=row.department
        this.handleSelectChangeDepotId();
        this.form.phonenum=row.phonenum
        this.form.email=row.email
        this.form.description=row.description
        this.form.remark=row.remark
      })
    },
    //进行更新操作
    doUpdate(){
      this.$axios.put('/zzh-staff/update',this.form).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.dialogVisible=false
          this.$message({
            showClose: true,
            message: '更新数据成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '更新数据失败',
            type: 'error'
          });
        }
      })
    },
    //进行删除操作
    del(id){
      this.$axios.delete('/zzh-staff/delete?id='+id).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '删除失败',
            type: 'error'
          });
        }
      })
    },
    //进行更新角色状态
    updateStatus(id){
      this.$axios.put('/zzh-staff/updateStatus?id='+id).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.$message({
            showClose: true,
            message: '更新状态成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '更新状态失败',
            type: 'error'
          });
        }
      })
    },
    //进行分页操作
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum=1
      this.pageSize=val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum=val
      this.loadPost()
    },
    //重新刷新
    resetParam(){
      this.username='';
      this.department='';
      this.selectedValue='';
      this.selectedNode=[];
      this.loadPost();
    },
    //重置窗体表单
    resetForm() {
      //通过this.$refs.form可以访问名为"form"的子组件或DOM元素
      //调用resetFields()方法将重置表单元素的值和校验状态，使表单恢复到最初的空白状态
      this.$refs.form.resetFields();
      this.selectedValue='';
      this.selectedNode=[];
      this.selectedValueDialog='';
      this.selectedNodeDialog=[];
    },
    //获取角色信息
    getPositionName(id){
      return this.hashMapRoles[id] || '';
    },
    //获取部门信息
    getDepartmentName(id){
      return this.hashMapOrganizations[id] || '';
    },
    //树节点数据赋值
    handleAddClick(data){
      this.selectedNode = [data]; // 将选中的节点数据赋值给selectedNode
      this.selectedValue = data.label; // 将选中的节点值赋值给selectedValue
      this.department=data.id;
    },
    //树节点数据赋值(弹窗)
    handleAddClickDialog(data){
      this.selectedNodeDialog = [data]; // 将选中的节点数据赋值给selectedNodeDialog
      this.selectedValueDialog = data.label; // 将选中的节点值赋值给selectedValueDialog
      this.form.department=data.id;
    },
    //数据筛选
    handleSelectChangeDepotId(){
      for (let key in this.hashMapOrganizations) {
        if (key === this.form.department) {
          this.selectedValueDialog = this.hashMapOrganizations[key]; // 将 key 设置为选中值
          break;
        }
      }
    },
  },
  beforeMount() {
    this.loadOption();
    this.loadPost();
  }
}
</script>

<template>
  <div>
    <!--    按钮-->
    <div style="margin-bottom: 5px">
      <el-input v-model="username" placeholder="请输入名字" suffix-icon="el-icon-search" style="width: 200px"
                @keyup.enter.native="loadPost"></el-input>
      <el-select v-model="selectedValue" placeholder="请选择上级机构" style="margin-left: 5px">
        <el-option
            v-for="item in TreeData" :key="item.id" :value="item.label" :label="item.label"
            v-show="false"></el-option>
        <el-tree
            v-model="selectedNode"
            :data="TreeData"
            :props="defaultProps"
            default-expand-all
            @node-click="handleAddClick"
        ></el-tree>
      </el-select>

      <el-button type="primary" style="margin-left: 5px" @click="loadPost">查询</el-button>
      <el-button type="success" @click="resetParam">重置</el-button>
      <el-button type="primary" style="margin-left: 5px" @click="add">新增</el-button>
      <el-button type="success" plain @click="exportExcel" style="margin-left: 10px" icon="el-icon-download">导出Excel</el-button>
    </div>
    <!--    表单-->
    <el-table :data="tableData" v-loading="loading"
              :header-cell-style="{background:'#f3f6fd',color:'#555'}">
      <el-table-column prop="id" label="id" width="140">
      </el-table-column>
      <el-table-column prop="loginName" label="登录名称" width="140">
      </el-table-column>
      <el-table-column prop="username" label="用户姓名" width="120">
      </el-table-column>
      <el-table-column prop="position" label="用户职位" width="120">
        <template slot-scope="scope">
          {{ getPositionName(scope.row.position) }}
        </template>
      </el-table-column>
      <el-table-column prop="department" label="部门" width="120">
        <template slot-scope="scope">
          {{ getDepartmentName(scope.row.department) }}
        </template>
      </el-table-column>
      <el-table-column prop="phonenum" label="电话号码" width="120">
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-tag
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              disable-transitions>{{scope.row.status === 1 ? '正常' : scope.row.status === 2 ? '禁用' : '已删除'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="operate" label="操作">
        <template slot-scope="scope">
          <span v-if="scope.row.id !== 1">
            <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm
              title="确定删除吗？"
              style="margin-left: 5px;margin-right: 5px"
              @confirm="del(scope.row.id)"
          >
            <el-button slot="reference" size="small" type="danger">删除</el-button>
          </el-popconfirm>
          <el-button size="small" type="success" @click="updateStatus(scope.row.id)">启用/禁用</el-button>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页条-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    <!--    提示框-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="40%"
        style="margin-top: -50px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="mini">
        <el-form-item label="登录名称" prop="loginName">
          <el-input v-model="form.loginName" placeholder="请输入登录名称"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户姓名"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="position">
          <el-select v-model="form.position" placeholder="请选择角色" style="width: 100%">
            <el-option v-for="(key,value) in hashMapRoles" :key="value" :label="key" :value="value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-select v-model="selectedValueDialog" placeholder="请选择上级机构" style="width: 100%">
            <el-option
                v-for="item in TreeData" :key="item.id" :value="item.label" :label="item.label"
                v-show="false"></el-option>
            <el-tree
                v-model="selectedNodeDialog"
                :data="TreeData"
                :props="defaultProps"
                default-expand-all
                @node-click="handleAddClickDialog"
            ></el-tree>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenum">
          <el-input v-model="form.phonenum" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱"></el-input>
        </el-form-item>
        <el-form-item label="用户描述信息" prop="description">
          <el-input v-model="form.description" placeholder="请输入用户描述信息"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false;">取 消</el-button>
        <el-button type="primary" @click="loadAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>
